package com.zbf.tspring.service;

import com.zbf.tspring.dao.TestDao;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Service;
import org.springframework.transaction.TransactionDefinition;
import org.springframework.transaction.TransactionStatus;
import org.springframework.transaction.annotation.Transactional;

import java.util.HashMap;
import java.util.Map;

/**
 * @author: LCG
 * 作者: LCG
 * 日期: 2021/3/22  8:34
 * 描述: 测试编程式式事务
 */
@Component
@Service
public class TestService {

    @Autowired
     private TestDao testDao;

    @Autowired
    private DataSourceTransactionManager dataSourceTransactionManager;

    @Autowired
    private TransactionDefinition transactionDefinition;



    /**
     * 作者: LCG
     * 日期: 2021/3/22  8:37
     * 描述: 编程式式事务的使用方式
     * @Param []
     * @Return void
     */
    @Transactional
    public void test01(int status){
        //开启事务
        TransactionStatus transaction = dataSourceTransactionManager.getTransaction(transactionDefinition);
        Map<String,Object> map=new HashMap<>();
        map.put("id",3);
        map.put("quantity",300);
        try {

            //更新base_order
            int i = testDao.updateOrder(map);

            if(status==1){
                throw new RuntimeException("=========异常-===========");
            }
            //提交事务
            dataSourceTransactionManager.commit(transaction);

        }catch (Exception e){

            e.printStackTrace();
            //回滚事务
            dataSourceTransactionManager.rollback(transaction);

        }


        //更新base_stock
        //int i1 = testDao.updateStock(map);

        ThreadLocal threadLocal=new ThreadLocal();

    }


}
